package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC443 {
    public long startExecuteTime = System.currentTimeMillis();

    class Solution {
        public int compress(char[] chars) {
            int curPos = 0, sameCount = 1;
            char lastChar = chars[0];
            for (int i = 1; i < chars.length; i++) {
                if (lastChar == chars[i]) {
                    ++sameCount;
                    continue;
                } else {
                    chars[curPos++] = lastChar;
                    if (sameCount > 1) {
                        char[] sameCountStrArray = String.valueOf(sameCount).toCharArray();
                        for (char bit : sameCountStrArray) {
                            chars[curPos++] = bit;
                        }
                    }
                    lastChar = chars[i];
                    sameCount = 1;
                }

            }

            chars[curPos++] = lastChar;
            if (sameCount > 1) {
                char[] sameCountStrArray = String.valueOf(sameCount).toCharArray();
                for (char bit : sameCountStrArray) {
                    chars[curPos++] = bit;
                }
            }
            return curPos;
        }
    }

    class Solution_Fuck_Author {
        public int compress(char[] chars) {
            int[] count = new int[128];
            for (char cur : chars) {
                count[((int) cur)]++;
            }

            int curPos = 0;
            for (int i = 0; i < 128; i++) {
                if (count[i] == 0) continue;
                if (count[i] == 1) {
                    chars[curPos++] = ((char) i);
                    continue;
                } else {
                    chars[curPos++] = ((char) i);
                    String num = String.valueOf(count[i]);
                    for (char bit : num.toCharArray()) {
                        chars[curPos++] = bit;
                    }
                }
            }

            return curPos;
        }
    }

    public void run() {
        Solution solution = new Solution();
        char[] arr = InputUtil.toCharArray("[\"a\",\"a\",\"a\",\"b\",\"b\",\"a\",\"a\"]");
        System.out.println(solution.compress(arr));
    }

    public static void main(String[] args) throws Exception {
        LC443 an = new LC443();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
